/*
 * @Description: 生成 vue useIndex
 * @Author: DHL
 * @Date: 2022-01-30 14:20:12
 * @LastEditors: DHL
 * @LastEditTime: 2022-08-22 10:47:23
 */

import {
  firstToUpperCase,
  firstToLowerCase,
  getVueDefaultValue,
  getAuthKey
} from '../../utils/codeGenUtils'
import { stringUtils } from '/@/utils/stringUtils'

export function createUseIndex(codeGenConfig: any) {
  const classNameFirstToUpperCase = firstToUpperCase(codeGenConfig.className)
  const classNameFirstToLowerCase = firstToLowerCase(codeGenConfig.className)
  const apiPath = codeGenConfig.apiPath
  const resName = classNameFirstToLowerCase
    .replace(/([A-Z])/g, '_$1')
    .trim()
    .replaceAll('_', '-')
    .toUpperCase()

  return `
/*
 * @Description: ${codeGenConfig.genName}
 * @Author: ${codeGenConfig.genAuthor}
 * @Date: ${codeGenConfig.createData}
 * @LastEditors: ${codeGenConfig.genAuthor}
 * @LastEditTime: ${codeGenConfig.createData}
 */

import { defineComponent, computed, reactive, ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { assign, cloneDeep } from 'lodash-es'
import { TwTableOptions } from '/@/types/table.d'
import { arraySerializeToStr } from '/@/utils/twUtils'
import { usePermission } from '/@/hooks/web/permission'
import {
  ${classNameFirstToUpperCase}Model,
  ${classNameFirstToUpperCase}PageParams
} from '/@/api/${apiPath}/model/${classNameFirstToLowerCase}Model'
import { api${classNameFirstToUpperCase}LogicBatchDeleteByIds, api${classNameFirstToUpperCase}Search, api${classNameFirstToUpperCase}Export } from '/@/api/${apiPath}/${classNameFirstToLowerCase}'
import ${classNameFirstToLowerCase}Form from './form.vue'

export default defineComponent({
  name: '${classNameFirstToUpperCase}',
  components: { ${classNameFirstToLowerCase}Form },
  setup(props) {
    //////////////////////////////////////////////////
    // 属性
    //////////////////////////////////////////////////

    const loading = ref(false)
    const loadingByDel = ref(false)

    // 权限控制
    const { hasPermission } = usePermission()

    /**
     * 表格数据
     */
    const tableData = ref()

    /**
     * 查询表单
     */
    const searchFormRef = ref()

    /**
     * 数据列表
     */
    const tableRef = ref()

    /**
     * 表单
     */
    const formRef = ref()

    /**
     * 公共
     */
    const state = reactive({ })

    /**
     * 是否有选中的行
     */
    const isSelectRows = computed(() => {
      let selectRows: Array<${classNameFirstToUpperCase}Model> = []
      if (tableRef.value) {
        selectRows = tableRef.value.getSelectRows()
      }
      return selectRows.length < 1
    })

    //////////////////////////////////////////////////
    // 查询表单
    //////////////////////////////////////////////////

    const defaultSearchForm = {
      queryLikeStr: '', // 模糊查询关键字
      ${getField(codeGenConfig.optionsJson.columns)}
    }

    /**
     * 查询表单
     */
    const searchForm = reactive(cloneDeep(defaultSearchForm))

    //////////////////////////////////////////////////
    // 表格
    //////////////////////////////////////////////////

    /**
     * 表格配置
     */
    const tableOptions = reactive<TwTableOptions>({
      id: '${classNameFirstToLowerCase}Table',
      sortConfig: {
        defaultSort: [{ field: 'updateDate', order: 'desc' }]
      },
      columns: [
        { type: 'checkbox', fixed:'left', title: '', width: 40 },
        { type: 'seq', fixed:'left', title: '序号', width: 50 },
        ${getTableColumns(codeGenConfig.optionsJson.columns)}
        { title: '操作', fixed:'right', width: 110, slots: { default: 'action' } }
      ]
    })

    /**
     * 绑定事件
     */
    const tableEvents = reactive({
      cellDblclick(params: { row: ${classNameFirstToUpperCase}Model }) {
        if (hasPermission('${getAuthKey(resName, 'view')}')) {
          handleOpenForm('view', params.row)
        } else {
          ElMessage.warning('无权限访问')
        }
      }
    })

    //////////////////////////////////////////////////
    // 函数
    //////////////////////////////////////////////////

    /**
     * 查询表格数据函数
     * @param queryParams
     */
    function searchList(queryParams: ${classNameFirstToUpperCase}PageParams) {
      loading.value = true
      api${classNameFirstToUpperCase}Search(assign(queryParams, searchForm))
        .then((result) => {
          tableData.value = result
        })
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 查询表格数据
     */
    function handleSearch() {
      tableRef.value.handleQuery()
    }

    /**
     * 刷新
     */
    function handleRefresh() {
      tableRef.value.handleReload()
    }

    /**
     * 重置
     */
    function handleReset() {
      assign(searchForm, cloneDeep(defaultSearchForm))
      tableRef.value.handleQuery()
    }

    /**
     * 批量删除
     */
    function handleDelete(row?: ${classNameFirstToUpperCase}Model) {
      let selectRows: Array<${classNameFirstToUpperCase}Model> = []

      if (row) {
        selectRows = [row]
      } else {
        selectRows = tableRef.value.getSelectRows()
      }

      if (selectRows.length === 0) {
        ElMessage.warning('请选择需要删除的数据')
        return
      }

      ElMessageBox.confirm(\`此操作将删除\${selectRows.length}条记录, 是否继续?\`, '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          loadingByDel.value = true
          const ids = arraySerializeToStr(selectRows, 'id')
          api${classNameFirstToUpperCase}LogicBatchDeleteByIds(ids)
            .then((result) => {
              if (result?.success) {
                handleRefresh()
                ElMessage.success(result.message)
              } else {
                ElMessage.error(result?.message)
              }
            })
            .catch(() => {})
            .finally(() => {
              loadingByDel.value = false
            })
        })
        .catch(() => {
          ElMessage.info('删除被取消了')
        })
    }

    /**
     * 弹出表单
     */
    function handleOpenForm(action: string, row?: ${classNameFirstToUpperCase}Model) {
      formRef.value.handleOpen(action, row)
    }

    /**
     * 导出
     */
    function handleExport(queryParams: ${classNameFirstToUpperCase}PageParams) {
      loading.value = true
      api${classNameFirstToUpperCase}Export(assign(queryParams, searchForm), '${codeGenConfig.genName
    }').finally(() => {
        loading.value = false
      })
    }

    //////////////////////////////////////////////////
    // 生命周期
    //////////////////////////////////////////////////
    onMounted(() => {})

    return {
      loading,
      loadingByDel,
      tableData,
      searchFormRef,
      tableRef,
      formRef,
      state,
      searchForm,
      tableOptions,
      tableEvents,
      isSelectRows,
      searchList,
      handleSearch,
      handleRefresh,
      handleReset,
      handleDelete,
      handleOpenForm,
      handleExport
    }
  }
})
`
}

/**
 * 获取字段
 * @param columns
 */
function getField(columns: any) {
  let field: Array<string> = []

  let searchArray: any[] = []

  columns.forEach((item: any) => {
    if (item.query) {
      searchArray.push(item)
    }
  })
  for (let i = 0; i < searchArray.length; i++) {
    const item = searchArray[i]

    if (i === searchArray.length - 1) {
      field.push(`${item.javaField}: null  // ${item.javaComment}`)
    } else {
      field.push(`${item.javaField}: null,  // ${item.javaComment}
      `)
    }
  }

  return field.join('')
}

/**
 * 获取表格列
 * @param columns
 */
function getTableColumns(columns: any) {
  let field: Array<string> = []

  let listArray: any[] = []

  columns.forEach((item: any) => {
    if (item.list) {
      if (stringUtils.isNotEmpty(item.dataDic)) {
        field.push(`{ field: '${item.javaField}', title: '${item.javaComment}', sortable: true, params: { dict: '${item.dataDic}' } },
        `)
      } else {
        field.push(`{ field: '${item.javaField}', title: '${item.javaComment}', sortable: true },
        `)
      }
    }
  })

  return field.join('')
}
